<template>
  <!-- 开提箱单 5-租箱 10-回调 15-外调 200-售箱 -->
  <el-row>
    <el-col :span="6">
      <span class="_before">开提箱单</span>
    </el-col>
  </el-row>
  <el-row align="middle" class="marginTop20">
      <el-col :span="12"><redStar />售箱订单</el-col>
      <el-col :span="12" v-if="drawerConfig.type == '1'"> 
        <el-button @click="getOrderTable" icon="edit" size="small" style="float: right;">选择订单</el-button>
      </el-col>
  </el-row>

  <el-row class="marginTop10">
    <el-col :span="24">
      <el-table :data="param.orderList" style="width: 100%;" >
        <el-table-column prop="orderNo" label="订单号" width="200" align="center"></el-table-column>
        <el-table-column label="预计提箱日期" align="center">
          <template #default="scope"> {{ formatDate(scope.row.planPickupDate, 2) }}</template>
        </el-table-column>
        <el-table-column label="下单日期"  align="center">
          <template #default="scope"> {{ formatDate(scope.row.createTime, 2) }} </template>
        </el-table-column>
        <el-table-column prop="packingAllocationQuantity" label="已开箱量" align="center"> </el-table-column>
        <el-table-column prop="boxQuantity" label="未开箱量" align="center">
          <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
        </el-table-column>
        
        <el-table-column label="需开箱量" v-if="param.orderList.length > 1" prop="needPackingNum" align="center">
          <template #default="scope">
            {{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}
          </template>
        </el-table-column>
        <el-table-column v-else label="需开箱量" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.needPackingNum" style="width: 100%;" />
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  
  <el-row class="marginTop20">
    <el-col :span="24" >箱型/箱况/箱量</el-col>
    <el-col :span="24">
      <el-table :data="param.rentBoxTable" border  style="width: 100%;margin-top: 10px;">
        <el-table-column prop="boxType" label="箱型" align="center"> </el-table-column>
        <el-table-column prop="boxCondition" label="箱况" align="center"> </el-table-column>
        <el-table-column prop="boxQuantity" label="箱量" align="center"> </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  
  <el-row class="marginTop20">
    <el-col :span="24"><redStar />提箱单有效范围</el-col>
    <el-col :span="16" class="marginTop10"> 
      <el-date-picker v-model="param.packingValidityPeriod" type="daterange" :disabled-date="disabledDate" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
    </el-col>
  </el-row>
  <div>
    <el-form :model="param" ref="packingFormRef" :rules="packingRules" style="margin-top: 40px;">
      <!-- 5-自有箱 15：外调箱 -->
      <template v-if="props.packingInfo.owned == 5"> <!-- -->
        <el-form-item prop="instruction">
          <div>
            <redStar />放箱指令号:
          </div>
          <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="packingValidityPeriod">
          <div>
            <redStar />提箱单有效期范围:
          </div>
          <el-date-picker v-model="param.packingValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item prop="yardName">
          <div>
            <redStar />堆场名称:
          </div>
          <yardSelect v-model="param.yardName" :selectName="'yardName'" :needInfo="true" @yardId="yardInfoData"
            style="width:100%" :placeholder="'请输入堆场名称'">
          </yardSelect>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场地址
          </div>
          <el-input v-model="yardInfo.yardAddress" disabled style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="contacts">
          <div>
            <redStar />联系人
          </div>
          <!-- <el-input v-model="yardInfo.contacts" disabled style="width: 100%;" placeholder="请输入"></el-input> -->
          <el-select v-model="yardInfo.contacts" @change="handleYardContactsChange">
            <el-option v-for="item in yardInfo.yardContacts" :key="item.yardContactSerialNo" :label="item.contacts"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />联系电话
          </div>
          <el-input v-model="yardInfo.tel" disabled style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />邮箱
          </div>
          <el-input v-model="yardInfo.email" disabled style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场作业时间
          </div>
          <el-input v-model="yardInfo.workTime" disabled style="width:100%" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <div style="padding: 40px 0;">
            <el-button @click="choiceBox" :disabled="!yardInfo.id" icon="edit" style="float: right;">选择箱号</el-button>
          </div>
          <el-table :data="selectBoxList">
            <el-table-column prop="containerNo" label="箱号" />
          </el-table>
        </el-form-item>
      </template>
      <!-- 15-外调 -->
      <template v-if="props.packingInfo.owned == 15">
        <el-form-item prop="packingValidityPeriod">
          <div>
            <redStar />提箱单有效期范围
          </div>
          <el-date-picker v-model="param.packingValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item>
          <div>集装箱公司名称</div>
          <el-input v-model="yardInfo.boxEast" style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <div>堆场名称</div>
          <el-input v-model="yardInfo.yardName" style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
      </template>
    </el-form>
  </div>
  <el-row class="marginTop20"> 
    <el-col :span="24" >箱号</el-col>
    <el-col :span="24">
        <el-input v-model="param.containerNo" :rows="5" type="textarea" placeholder="请输入箱号（每个箱号之间适用'/'隔开）" @blur="checkContainerNo"/>
    </el-col>
  </el-row>
  <div style="margin-top: 40px;">
    <div>提箱单附件<span style="font-size: 12px;color: #ff0000;margin-left: 10px;"></span></div>
    <ImgUpload ref="packingRef" :displayType="2" :urlList="fileList" :fileSize="3" :limit="10" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :drag="true"/>
  </div>
  <div style="margin-top: 40px;">
    <div>备注</div>
    <el-input v-model="param.remark" type="textarea" placeholder="请输入内容" />
  </div>
  <div style="margin-top: 40px;height: 50px;">
    <el-button @click="handleSubmit" type="primary" style="float: right;width: 100px;">提交</el-button>
  </div>

  <!-- 集装箱选择 -->
  <el-drawer v-model="param.drawerSelectBox" :with-header="false">
    <span style="font-weight: 700;font-size: 15px;">
      <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>集装箱选择
    </span>
    <el-input v-model="param.containerNo" @input="getBoxTableData" type="text" placeholder="请输入箱号"
      style="float: right;margin-top: 40px;" />
    <div style="height:40px"></div>
    <el-table :data="param.selectBoxTable" @selection-change="handleSelectionBoxChange" style="margin-top: 90px;">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="containerNo" label="箱号" width="200"> </el-table-column>
      <el-table-column prop="boxType" label="箱型" width="180"> </el-table-column>
      <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
      <el-table-column prop="inDays" label="堆存天数" width="180"> </el-table-column>
    </el-table>
    <div style="margin-top: 40px;height: 50px;">
      <el-button @click="handleChoiceBox" type="primary" style="float: right;width: 100px;">确定</el-button>
    </div>
  </el-drawer>

  <!-- 订单选择 -->
  <el-drawer v-model="param.drawerSelectOrder" size="50%" :with-header="false">
    <div class="marginBottom20" >
      <span class="_before">订单选择</span>
    </div>
    <el-form v-if="param.orderDisabled" inline class="marginBottom30" style="float: right;">
      <el-form-item v-if="packingInfo.orderType != 200" label="提箱城市" style="width:200px">
        <city-select ref="startCityRef" v-model="searchForm.carryCityId" :needInfo="true" :cityList="startCityList"
          @cityId="startCityInfo" style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item label="箱型" style="width:150px">
        <el-select v-model="searchForm.boxType" @change="getOrderTable" style="width:100%" placeholder="选择箱型">
          <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="箱况" style="width:150px">
        <el-select v-model="searchForm.boxCondition" @change="getOrderTable" style="width:100%" placeholder="选择箱况">
          <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="searchLabel" >
        <el-input v-model.trim="searchForm.agentName" @input="getOrderTable" type="text" placeholder="请输入企业名称" :suffix-icon="Search"/>
      </el-form-item>
    </el-form>
    <el-table ref="selectTable" :data="param.selectTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="orderNo" label="订单号" width="150" align="center"/>
      <el-table-column prop="carryCityName" label="提箱城市" width="80" align="center"/>
      <el-table-column prop="boxType" label="箱型" width="80" align="center"/>
      <el-table-column prop="boxCondition" label="箱况" width="80" align="center"/>
      <el-table-column label="总重（KG）" width="100" align="center">
        <template #default="scope">
          {{ scope.row.boxType <= 10 ? '30480/32500KG' : '30480KG' }} </template>
      </el-table-column>
      <el-table-column label="箱量" width="60" align="center">
        <template #default="scope" >{{ scope.row.boxQuantity }}</template>
      </el-table-column>
      <el-table-column label="预计提箱日期" width="120" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.planPickupDate, 2) }} </template>
      </el-table-column>
      <el-table-column label="下单日期" width="120" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }} </template>
      </el-table-column>
      <el-table-column prop="agentName" v-if="props.packingInfo.orderType == 5" label="客户" align="center"/>
      <el-table-column prop="agentName" v-if="props.packingInfo.orderType == 10" label="客户" align="center"/>
      <el-table-column prop="buyBoxCompanyName" v-if="props.packingInfo.orderType == 200" label="客户" align="center"/>
      <template #empty><el-empty description="请尝试选择其它箱型/箱况" /></template>
    </el-table>
    <div style="margin-top: 40px;">
      <el-button @click="handleChoiceOrder" type="primary" style="float: right;width: 100px;">确定</el-button>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { formatDate, getDaysDifference } from '@/utils'
import redStar from '@/views/components/redStar.vue';
import { numAdd, numSub, numMulti } from '@/utils/compute'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref, watch } from 'vue';
import yardSelect from '@/components/citySelect/yardSelect.vue';
import citySelect from '@/components/citySelect'
import { getTable as getBoxTable } from '@/api/boxManage/index'
import { getTableBoxOwner as boxEastPage, boxEastPackingListPage } from '@/api/boxServer'
import { getBoxEastSelfTable as getHuiDiaoOrders, boxEastSelfCallbackOrderPackingListPage } from '@/api/boxCallBack/order'
import { getSellPurchaseBoxOrderPage as getSellBoxOrders } from '@/api/boxDeal/boxBuy'
import { addPacking } from '@/api/orderManage/packing'
import { addPackingBoxSell } from '@/api/boxDeal/tiXiangManage'
// import imgUpload from '@/components/upload/index.vue'
import ImgUpload from '@/components/upload/uploadFiles-Images.vue'
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
const emit = defineEmits(['successPacking'])
// onActivated(()=>{
//   param.packingValidityPeriod = null
// })

//props.packingInfo.orderType 5 - 租箱 10 - 回调 15 - 外调 （200 - 售箱）
const props = defineProps({
  packingInfo: {
    type: Object,
    default: () => {}
  },
  isPitch: { //是否 订单多选
    type: Boolean,
    default: false
  },
  drawerConfig: {
    type: Object,
    default: () => { }
  }
})

const startCityList = ref([])
const param = reactive({
  newStep: 5,
  drawerSelectBox: false,
  drawerPacking: false,
  drawerSelectOrder: false,
  orderList: [],//开提箱单订单列表
  rentBoxTable: [],
  selectTable: [{ orderNo: '', planPickupDate: '', createTime: '', boxType: '', boxQuantity: '', boxCondition: '' }],
  selectBoxTable: [{ containerNo: '', boxType: '', inDays: '', boxCondition: '' }],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '5', label: '全新', },
    // { value: '20', label: '混提', },
  ],
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  radioVal:"5", // 5 自由箱 15: 外调箱
  orderDisabled: true, // 订单弹窗筛选项是否可用
  totalNum:  0,
  containerNo:''
})


watch(() => props.packingInfo, (newVal, oldVal) => {
  if(props.drawerConfig.type == 0){
    param.orderList = []
    param.orderList.push(newVal)
  }else{
    // searchForm.boxType = drawerConfig.boxType
    // searchForm.boxCondition = drawerConfig.boxCondition
    param.orderList = []
    // param.packingValidityPeriod = null
  }
},{immediate:true})
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() -  86400000
}

const getOrderTable = () => {  // 获取订单列表
  const data = {
    pageNum: 1,
    pageSize: 200,
    agentName: searchForm.agentName,
    boxType: searchForm.boxType,
    boxCondition: searchForm.boxCondition,
    carryCityId: searchForm.carryCityId,
    sortBeans: [{ "field": "createTime", "isAsc": "asc" }] // desc 降序  asc 升序
  }
  const orderType = props.packingInfo.orderType  // 5:租箱 10：回调箱
  if (orderType == 5) { // 5:租箱 
    boxEastPackingListPage(data).then(res => {
      let list = res.data.list;
      list.forEach((el: any) => {
        el.boxType = boxTypeFilter(el.boxType)
        el.boxCondition = boxConditionFilter(el.boxCondition)
        const plus_areaCode = el.areaCode ? ' + ' + el.areaCode : ''
        el.areaTel = plus_areaCode + el.tel
      });
      param.selectTable = list
    });
  }
  if (orderType == 10) { // 10：回调箱
    data.agentName = ""
    data.boxType = props.packingInfo.boxType
    data.boxCondition = props.packingInfo.boxCondition
    param.orderDisabled = false
    boxEastSelfCallbackOrderPackingListPage(data).then(res => {
      let list = res.data.list;
      param.totalNum = 0
      list.forEach((el: any) => {
        el.boxType = boxTypeFilter(el.boxType)
        el.boxCondition = boxConditionFilter(el.boxCondition)
      });
      param.selectTable = list
    });
  }
  if (orderType == 200) { //200 - 售箱
    data.status = 20
    getSellBoxOrders(data).then(res => {
      let list = res.data.list;
      list.forEach((el: any) => {
        el.boxType = boxTypeFilter(el.boxType)
        el.boxCondition = boxConditionFilter(el.boxCondition)
      });
      param.selectTable = list
    });
  }
  param.drawerSelectOrder = true
}



//赋值列表（批量开）------
let selectList = ref([])
let selectTable = ref()
// 选择订单
const handleSelectionChange = (selection: any) => {
  const orderType = props.packingInfo.orderType
  if(orderType == 200){
    selectTable.value = selection
    selectList.value = selection
  }else{
    if (selection.length > 1) {
        // 如果勾选了多项，清空之前的勾选
        selectTable.value.clearSelection();
        // 只保留最后一项
        selectTable.value.toggleRowSelection(selection[selection.length - 1]);
      }
      selectList.value = selection.length ? [selection[selection.length - 1]] : [];
  }
}


const handleChoiceOrder = () => {
  param.drawerSelectOrder = false
  param.orderList = []
  param.rentBoxTable = []
  param.totalNum = 0
  if(param.orderList.length == 0){
    param.orderList = [...selectList.value]
    param.orderList.forEach(item => {
      item.needPackingNum = item.boxQuantity - item.packingAllocationQuantity
    })
  }else{
    param.orderList.push(selectList.value)
    // selectList.value.forEach(item => {})
  }
  selectList.value.forEach((el: any) => {
    param.totalNum = param.totalNum + (el.boxQuantity - 0)

  })
  let orderList = {
    boxType: boxTypeFilter(searchForm.boxType),
    boxCondition: boxConditionFilter(searchForm.boxCondition),
    boxQuantity: param.totalNum
  }

  param.rentBoxTable.push(orderList)
 
}



// *******************************************************************************************

const searchLabel = computed(() => {
  switch (props.packingInfo.orderType) {
    case 5:
      searchForm.placeholder = '请输入货代企业名称'
      searchForm.titleName = '租箱订单选择'
      return '客户'
    case 10:
      searchForm.placeholder = '请输入客户企业名称'
      searchForm.titleName = '回调箱订单选择'
      return '客户'
    case 15:
      searchForm.placeholder = '请输入货代企业名称'
      searchForm.titleName = '租箱订单选择'
      return '客户'
    case 20:
      searchForm.placeholder = '请输入客户名称'
      searchForm.titleName = '订单选择'
      return '客户'
    default:
      return ''
  }
})






//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  // if (value[0] < new Date(new Date().setHours(0, 0, 0, 0))) {
  if (value[0] < new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('开始日期 须不小于今天'))
  }
  if (getDaysDifference(value[1]) > 365) {
    return callback(new Error('时间间隔不超过365天'))
  }
  return callback()
}
const packingRules = {
  instruction: [
    { required: true, trigger: "blur", message: "不能为空" },
    { pattern: /^[0-9a-zA-Z]{1,20}$/, trigger: "blur", message: "1-20位数字/字母" }
    // { pattern: /[1-9a-zA-Z]{1}[0-9a-zA-Z]{0,20}/g, trigger: "blur", message: "0-20位数字/字母" }
  ],
  packingValidityPeriod: [{ required: true, trigger: "blur", message: "不能为空" },
  { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
  yardName: [{ required: true, trigger: "change", message: "不能为空" }],
  contacts: [{ required: true, trigger: ["change", "blur"], message: "不能为空" }],
}



// 获取城市和库存 
const startCityInfo = (id: any, data: any) => {
  searchForm.carryCityId = id
  getOrderTable()
}

//查询 租箱/外调/回调 订单列表
const searchForm = reactive({
  agentName: '',
  boxType: '5',
  boxCondition: '5',
})


// 获取列表------
// 订单列表
const getRentOrderTable = (packing: any, isPitch = false) => {
  const template = {
    orderNo: packing.orderNo?.trim(),
    planPickupDate: packing.planPickupDate,
    createTime: packing.createTime,
    id: packing.id,
    packingedNum: packing.packingAllocationQuantity || 0,
    unPackingNum: numSub(packing.boxQuantity, packing.packingAllocationQuantity),
    // needPackingNum: packing.boxQuantity - packing.packingAllocationQuantity,
    needPackingNum: numSub(packing.boxQuantity, packing.packingAllocationQuantity),
    // boxQuantity: packing.boxQuantity || 0 //numSub
  }
  if (isPitch) {
    return template
  } else {
    return [template]
  }
}

//获取 箱型/箱况/箱量 列表
const getRentBoxTable = (list: any) => {
  param.totalNum = 0
  if (list) {
    let boxArry: any = []
    list.forEach((el: any, index) => {
      param.totalNum = param.totalNum + (el.number - 0)
      if (index == list.length - 1) {
        boxArry.push({ boxType: boxTypeFilter(el.boxType), boxQuantity: param.totalNum, boxCondition: boxConditionFilter(el.boxCondition) })
      }
    });
    return boxArry
  }
}

//赋值列表（单开）------
const setTable = () => {
  param.orderList = []
  param.rentBoxTable = []
  if (!props.isPitch) { // 单开箱
    const packing = props.packingInfo
    const list = props.packingInfo.priceList
    param.orderList = getRentOrderTable(packing)
    param.rentBoxTable = getRentBoxTable(list)
    // handleSelectionBoxChange([{ "containerId": el.id, "containerNo": el.containerNo }])
  }

}





//堆场组件 emit 
const yardInfo = ref({})
const yardInfoData = (id: string, info: any) => {
  if (info) {
    param.yardName = info.yardName
    yardInfo.value.yardContacts = info.yardContacts ? JSON.parse(info.yardContacts) : []
    yardInfo.value.yardAddress = info.yardAddress
    yardInfo.value.workTime = info.workTime
    yardInfo.value.id = info.id
    //获取联系人&&默认第一个
    handleYardContactsChange(yardInfo.value.yardContacts[0])
  }
}

//获取 箱子列表
function getBoxTableData() {
  let data = {
    statusList: [5], //堆存中
    containerNo: param.containerNo,
    // boxType: props.packingInfo.boxType - 0,
    // boxCondition: props.packingInfo.boxCondition - 0,
    boxEastYardId: yardInfo.value.id,
    pageNum: 1,
    pageSize: 200,
  };
  if (props.isPitch) {
    data.boxType = searchForm.boxType - 0
    data.boxCondition = searchForm.boxCondition - 0
  } else {
    data.boxType = props.packingInfo.boxType - 0
    data.boxCondition = props.packingInfo.boxCondition - 0
  }
  getBoxTable(data).then(res => {
    let list = res.data.list;
    list.forEach((el: any) => {
      el.boxType = boxTypeFilter(el.boxType)
      el.boxCondition = boxConditionFilter(el.boxCondition)
    });
    param.selectBoxTable = list;
  });
}

//选择集装箱
const choiceBox = () => {
  getBoxTableData()
  param.drawerSelectBox = true
}

const handleChoiceBox = () => {
  param.drawerSelectBox = false
}

let selectBoxList = ref([])
const handleSelectionBoxChange = (list: any) => {
  selectBoxList.value = list
}

//开提箱单
const { proxy } = getCurrentInstance();
const handleSubmit = () => {
  let orderList = formatOrderList(param.orderList)
  if (orderList.length == 0) {
    return ElMessage.warning('请选择 操作订单')
  }
  if(!isPass) return '请检查箱号'
  proxy.$refs.packingFormRef.validate(valid => {
    if (!valid) return
    if (props.packingInfo.orderType == 200) {
      handleAddPackingSellBox(orderList)
    }
    // if ([5,10].includes(props.packingInfo.orderType)) {
    //   handleAddPacking(orderList)
    // }
    param.drawerPacking = false
  })

}
function formatOrderList(list: any) {
  let orderList: any[] = []
  list.forEach((el: any) => {
    if(props.packingInfo.orderType == 200){
      orderList.push({
         "orderId": el.id, 
         "orderNo": el.orderNo, 
         "planPickupDate": el.planPickupDate, 
         "createTime": el.createTime, 
         "boxQuantity": el.boxQuantity,
         "needPackQuantity": el.needPackingNum
        })
    }else{
      orderList.push({ 
        "orderId": el.id, 
        "orderNo": el.orderNo, 
        "planPickupDate": el.planPickupDate, 
        "createTime": el.createTime, 
        "boxQuantity": el.boxQuantity, 
        needPackQuantity: el.needPackingNum 
      })
    }
  })
  return orderList
}

//开提箱单-租箱/回调/外调 
const packingRef = ref()
const handleAddPacking = async (orderList: any) => {
  if (param.rentBoxTable.length == 0) {
    return ElMessage.warning('箱型/箱量/箱况 不能为空')
  }
  if (!param.rentBoxTable[0].boxQuantity) {
    return ElMessage.warning('箱量 不能为空')
  }
  let containerNoList: any[] = []
  selectBoxList.value.forEach((el: any) => {
    containerNoList.push({ "containerId": el.id, "containerNo": el.containerNo })
  })
  const imgList = await packingRef.value.fileList || []
  let data = {
    orderType: props.packingInfo.orderType, // 5-租箱(自有)   10-回调
    "containerNo": param.containerNo,
    totalQuantity: param.rentBoxTable[0].boxQuantity,
    "orderList": JSON.stringify(orderList),
    "instruction": param.instruction,
    "packingValidityPeriodStart": param.packingValidityPeriod[0],
    "packingValidityPeriodEnd": param.packingValidityPeriod[1],
    "boxEastYardId": yardInfo.value.id,
    "containerNoList": JSON.stringify(containerNoList) || null, //"[{\"containerId\":1,\"containerNo\":\"2222\"}]" jc0706
    "remark": param.remark,
    "packingFileList": JSON.stringify(imgList) || null,
    yardContactSerialNo: yardInfo.value.yardContactSerialNo,
    "containerClassify":props.packingInfo.owned  // 5:自有箱  15：外调箱 
  }
  if (props.isPitch) {
    data.boxCondition = searchForm.boxCondition - 0
    data.boxType = searchForm.boxType - 0
  } else {
    data.boxCondition = props.packingInfo.boxCondition
    data.boxType = props.packingInfo.boxType
  }
  if (props.packingInfo.owned == 15) {  //开外调提箱单时 
    data.yardName = yardInfo.value.yardName
    data.outBoxCompanyName = yardInfo.value.boxEast
  }
  addPacking(data).then((res: any) => {
    param.packingId = res.data.id
    emit('successPacking', res.data.id)
  })
}

//开提箱单-售箱
const handleAddPackingSellBox = async (orderList: any) => {
  const imgList = await packingRef.value.fileList || []
  const data = {
    boxType: searchForm.boxType - 0,
    boxCondition: searchForm.boxCondition - 0,
    orderList: JSON.stringify(orderList), //"[{\"orderId\":1,\"orderNo\":\"2222\"}]", jc0706
    packingFileList: JSON.stringify(imgList) || null,
    packingValidityPeriodStart: param.packingValidityPeriod[0],
    packingValidityPeriodEnd: param.packingValidityPeriod[1],
    remark: param.remark,
    containerNo:formattedContainer(param.containerNo)
  }
  addPackingBoxSell(data).then((res: any) => {
    param.packingId = res.data.id
    emit('successPacking', res.data.id)
  })
}

//联系人切换
const handleYardContactsChange = (val: any) => {
  if (!val) return
  yardInfo.value.contacts = val.contacts
  param.contacts = val.contacts //  to pass jiaoyan
  yardInfo.value.tel = val.tel
  yardInfo.value.email = val.email
  yardInfo.value.yardContactSerialNo = val.yardContactSerialNo
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: '5', label: '40HQ' }, { value: '10', label: '40GP' }, { value: '15', label: '20HQ' }, { value: '20', label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

const isPass = ref(true) // 输入的箱号是否合规
const checkContainerNo = () =>{ 
  formattedContainer(param.containerNo)
}

const formattedContainer = (containerNumber:string) =>{ //处理检查箱号
    isPass.value = true
    if(containerNumber){
        containerNumber =  containerNumber.replace(/\s/g, '') // 去掉所有空格  
        containerNumber =  containerNumber.replace(/\//g, ',')// 把所有斜杠替换成英文逗号
        let containerNumberArr: string[]  = containerNumber.split(",")
        containerNumberArr.forEach((item,index) => {
            const regExp = /^[A-Z]{3}U\d{7}$/
            if(!regExp.test(item)){
              isPass.value = false
                ElMessage({
                    type:'warning',
                    message:`请检查输入的第${index + 1}个箱号是否正确`,
                    duration:5000
                })
            }
        })
        return containerNumber
    } 

    return containerNumber
}
</script>
